import { Button,Row,Col, Modal} from 'antd';
import { WeaTools,WeaSearchGroup,WeaRightMenu,WeaFormItem,WeaTop, WeaCheckbox, WeaSelect, WeaDatePicker,WeaDialog,WeaLocaleProvider, WeaAlertPage} from 'ecCom'
import isEmpty from 'lodash/isEmpty'
import forEach from 'lodash/forEach'
import {WeaSwitch} from 'comsMobx';
import { inject, observer} from 'mobx-react';
import * as mobx from 'mobx';
import moment from 'moment';
import "../../style/systeminfo.less";
import InputBtn from '../../coms/inputBtn'
import NeedAutoBtn from '../../coms/needAutoBtn'
import TopButton from '../../coms/topButton';
import {i18n} from '../../public/i18n';
const getKey = WeaTools.getKey;
const toJS = mobx.toJS;
const confirm = Modal.confirm;
const getLabel = WeaLocaleProvider.getLabel;

@inject('hrmSystemInfo')
@inject('hrmCard')
@observer
class HrmSystemInfo extends React.Component {
  componentDidMount(){
    const {hrmSystemInfo,hrmCard} = this.props;
    hrmSystemInfo.init();
    hrmSystemInfo.hrmId = this.props.params.hrmId || '';
    hrmSystemInfo.getFormField();
    hrmSystemInfo.getWeekInfo(new moment().format('YYYY-MM-DD'));
    const dom = $('<Object id="htactx" name="htactx" classid="clsid:FB4EE423-43A4-4AA9-BDE9-4335A6D3C74E" codebase="HTActX.cab#version=1,0,0,1" style="HEIGHT: 0px; WIDTH: 0px"></Object>');
    $(document.body).append(dom);

    hrmCard.setTopButtons(this.getTopButtons.bind(this));
    hrmCard.setTopRightMenus(this.getRightMenu.bind(this));
    hrmCard.setTopShowDropIcon(true);
  }

  getSearchs = () => {
    const {hrmSystemInfo} = this.props;
    let {isEditor, checkValue, inputVlaue, pickerValue, selectValue, options, formFields, form} = hrmSystemInfo;
    const formParams = hrmSystemInfo.getFormParams();
    const userUsbType = formParams.userUsbType || '';
    const usbState = formParams.usbstate || '';
    const {date} = hrmSystemInfo;
    const cancelSecondPwd = () => {
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: (<div><div>{i18n.label['388923']()}</div><div>{i18n.label['388924']()}</div></div>),
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            width: 420,
            onOk: () => {
                form.updateFields({
                    useSecondaryPwd: {
                        value: '0'
                    }
                })
            }
        });
    }

    const {isFormInit} = form;
    let group = [];
    let group1 = [];
    let colIndex = 1;
    let is901 = userUsbType == '901' ;
    if (is901 && (['tokenKey','serial'].indexOf(domkey) >= 0)){
        hide=true ;
    } 

    isFormInit && formFields.forEach((c, i) =>{
        c.items.forEach( (field, j) => {
            let domkey = field.domkey[0] || '';
            let hide = false;
            let hideLabel = false;

            if (userUsbType == '' && (domkey == 'tokenKey' || domkey == 'serial' || domkey == 'usbstate')) hide = true;
            if (userUsbType == '4' && (domkey == 'tokenKey' || domkey == 'serial')) hide = true;
            if (userUsbType == '2' && domkey == 'tokenKey') hide = true;
            if (userUsbType == '3' && domkey == 'serial') hide = true;
            if (!isEditor && (domkey == 'password'||domkey == 'password1')) hide = true;
            if (domkey === 'validatecode') {
                hide = isEditor ? false : true;
            }

            if(domkey == 'startUsing'){
                hide = true;
                if (isEditor && (userUsbType == '2' || userUsbType == '3') && usbState =='1' ){
                    hide = false;
                }
            }

            if(!hide){
                let dom;
                if (isEditor && domkey == 'tokenKey') {
                    hideLabel = true;
                    const key = getKey(field);
                    const bindObj = form.$(key);
                    dom = <div>
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@6upm3y@${j}`}>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@w0vegb@${j}`} span={7}>
                                <span>{i18n.label.tokenNum()}: </span>
                            </Col>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@kgvgrf@${j}`} span={17} >
                                <InputBtn ecId={`${this && this.props && this.props.ecId || ''}_InputBtn@pmgic4`} btnText={i18n.label.binding()} {...bindObj.bind()} viewAttr={3} onBtnClick={(v)=>this.updateKey()}/>
                            </Col>
                            </Row>
                           </div>
                } else if (isEditor && domkey == 'serial') {
                    hideLabel = true;
                    const key = getKey(field);
                    const bindObj = form.$(key);
                    dom = <div>
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@lbznbw@${j}`}>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@87ua9e`} span={7}>
                                <span>{i18n.label.userKey()}: </span>
                            </Col>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@knqvek`} span={17} >
                                <InputBtn ecId={`${this && this.props && this.props.ecId || ''}_InputBtn@df8u60`} btnText={i18n.label.binding()} {...bindObj.bind()} viewAttr={3} onBtnClick={(v)=>this.updateKey(v)}/>
                            </Col>
                            </Row>
                           </div>
                }else if (isEditor && domkey == 'startUsing') {
                    hideLabel = true;
                    dom = <div>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@6mco6k`}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@myse3s`} span={6}>
                      <span>{i18n.label.autoEnable()}：</span>
                    </Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@6b25js`} span={18} >
                    <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@b3s14s`} display='switch' value={checkValue} onChange={this.onCheckChange}/>
                    </Col>
                    </Row>
                    {
                         checkValue && checkValue=='1' && <div> 
                         <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@iosm81`}>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@yc9x5b`} span={6}>
                            <span>{i18n.label.enableDate()}：</span>
                            </Col>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@twp9ko`} span={18} >
                            <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@hkl5xz`} noInput startValue={new Date()} viewAttr={3} value={pickerValue} onChange={this.onPickerChange}/>
                            </Col>
                            </Row>
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@wz97ap`}>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@vaqfu4`} span={6}>
                            <span>{i18n.label.enableMode()}：</span>
                            </Col>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zs52vc`} span={18}>
                            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@iunzr8`} options={options} viewAttr={3} value={selectValue} onChange={this.onSelectChange}/>
                            </Col>
                        </Row>
                        </div>
                   }
                  </div>
                }else if(domkey=='useSecondaryPwd'){
                    dom = (
                        <div className='wea-field-readonly'>{formParams.useSecondaryPwd === '1' ? i18n.label['15809']() : i18n.label['15808']()}</div>
                    );
                }else {
                    dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@r98afq`} fieldConfig={field} form={form} />
                }
                
                if(!isEditor){
                    if(colIndex % 2 == 0){
                        group1.push( <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@dvmpr5@${j}`}
                            underline
                            label={`${field.label}`}
                            labelCol={{span: `${window.HrmLabelCol}`}}
                            wrapperCol={{span: `${window.HrmWrapperCol}`}}>
                            {dom}
                            </WeaFormItem>);
                    }else{
                        group.push( <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@cgltxr@${j}`}
                            underline
                            hideLabel={hideLabel}
                            label={`${field.label}`}
                            labelCol={{span: `${window.HrmLabelCol}`}}
                            wrapperCol={{span: `${window.HrmWrapperCol}`}}>
                            {dom}
                            </WeaFormItem>); 
                    } 
                    colIndex++;
                }else{
                    if(domkey=='password' || domkey=='password1' || domkey=='seclevel'){
                        group1.push( <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@z2nlet@${j}`}
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                            {dom}
                            </WeaFormItem>);
                    }else if(domkey=='useSecondaryPwd'){
                        group1.push( <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@4rwxlc@${j}`}
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                                <div>
                                    <div style={{float: 'left', lineHeight: '30px', marginRight: '30px'}}>{formParams.useSecondaryPwd === '1' ? i18n.label['15809']() : i18n.label['15808']()}</div>
                                    {
                                        formParams.useSecondaryPwd === '1' &&
                                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4f0yly@${j}`} style={{float: 'left'}} type='primary' onClick={() => cancelSecondPwd()}>{i18n.label['26471']()}</Button>
                                    }
                                </div>
                            </WeaFormItem>);
                    }else if(domkey === 'validatecode'){
                            group1.push(
                                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@6tblem@${j}`}
                                                label={`${field.label}`}
                                                labelCol={{span: `${field.labelcol}`}}
                                                wrapperCol={{span: `${field.fieldcol}`}}>
                                                {dom}
                                                <img 
                                                  src={`/weaver/weaver.file.MakeValidateCode?isView=1&validatetype=0&validatenum=4&seriesnum_=${date}`}
                                                  style={{cursor:'pointer', position:'absolute', top: -5, left: '105%'}} 
                                                  onClick={() => hrmSystemInfo.date = new Date().getTime()}
                                                />  
                                            </WeaFormItem>
                            )
                    }else if(is901 && domkey == 'usbstate'){
                            let statesOptions = Array.from(field.options) ;
                            statesOptions.pop()
                            
                            group.push(
                                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@nbtdow@${j}`}
                                    hideLabel={hideLabel}
                                    label={field.label}
                                    labelCol={{span:field.labelcol}}
                                    wrapperCol={{span:field.fieldcol}}
                                >
                                     <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@m6ws73@${j}`}
                                            options={statesOptions}
                                            value={field.value}
                                            onChange={(v,showname)=>{this.changeUsbstate(v)}}
                                        />
                                </WeaFormItem>
                            );
                    } else {
                        group.push( <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@klvlk1@${j}`}
                            hideLabel={hideLabel}
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                            {dom}
                            </WeaFormItem>); 
                    } 
                }
            }
        });
    });

    return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@zlg9x9`}>
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ga671o`} span={12}>{group}</Col>
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@lzrirb`} span={12}>{group1}</Col>
    </Row>
  }

    render() {
        const {hrmSystemInfo} = this.props;
        const {viewDate, isEditor, weekInfo, title,weakPasswordDisable,doSave,changeModalState,modalVisible} = hrmSystemInfo;
        const formParams = hrmSystemInfo.getFormParams();
        const {query} = this.props.location;
        if(!query.fromcard && window.location.href.indexOf("/spa/hrm/index_mobx.html")>-1){
            document.title=i18n.label.sysInfo();
        }

        try{
            const weakPassBtns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@l95rjt@1`} type="primary" onClick={() => {
                    changeModalState(false);
                    (weakPasswordDisable === "0") &&  doSave(true)
                    }}>{i18n.button.ok()}</Button>,
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wkh6tt@1`} onClick={() => changeModalState(false)}>{i18n.button.cancel()}</Button>
            ]

            return (
                <div className='wea-myhrm-systeminfo wea-myhrm' style={{background: '#ffffff',height:'100%', position: 'relative'}}>
                <div style={query.fromcard? {display:'none'} :  {display:''}}>
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@gw5153`}
                    title={title()}
                    icon={<i className='icon-coms-hrm' />}
                    iconBgcolor='#217346'
                    buttons={this.getTopButtons()}
                    buttonSpace={10}
                    showDropIcon={true}
                    dropMenuDatas={this.getRightMenu()}
                />
                </div>
                <div className='hrm-my-card-basicInfo hrm-my-cardInfo wea-myhrm-systeminfo'>
                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@lotgy6`} needTigger={true} title={i18n.label.sysInfo()} showGroup={true}>
                    {this.getSearchs()}
                </WeaSearchGroup>
                    {
                        !isEditor && weekInfo && !isEmpty(weekInfo) &&
                        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@9mvjyw`}
                            needTigger={true}
                            title={i18n.label.sysLogiInfo()}
                            showGroup={true}
                            className="wea-sys-table"
                        >
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@m7pxfc`} className="bord-line total">
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@khnxit`} span = {4}>
                                    {i18n.label.weekSituation()}
                                </Col>
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@nhyri7`} span = {4}>
                                    {weekInfo.kqinfo.weekworkdayslabel}:{weekInfo.kqinfo.weekworkdays}
                                </Col>
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@enw5b6`} span = {4}>
                                    {weekInfo.kqinfo.weeksigninnumlabel}:{weekInfo.kqinfo.weeksigninnum}
                                </Col>
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@oncmxv`} span = {4}>
                                    {weekInfo.kqinfo.weeksignoutnumlabel}:{weekInfo.kqinfo.weeksignoutnum}
                                </Col>
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@45ypdl`} span = {4}>
                                    {weekInfo.kqinfo.weekblogwritenumlabel}:{weekInfo.kqinfo.weekblogwritenum}
                                </Col>
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@tm6hjh`} span = {4}>
                                    {weekInfo.kqinfo.weekblognotwritenumlabel}:{weekInfo.kqinfo.weekblognotwritenum}
                                </Col>
                            </Row>
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@f6kzon`} className="header" style={{height: 70}}>
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@uza2wy`} span = {3} style={{lineHeight: '70px'}}>
                                {viewDate && viewDate.slice(0, 7)}
                                </Col>
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@dxfu4v`} span = {3} className="picker-col" style={{lineHeight: '70px'}}>
                                    <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@mae5i8`} type="week" label={hrmSystemInfo.getDateLabel()} arrow date={viewDate} onChange={(v)=>hrmSystemInfo.onPickerHandler(v)}/>
                                </Col>
                                {
                                    weekInfo.weekInfo && !isEmpty(weekInfo.weekInfo) && weekInfo.weekInfo.map((item, i) => {
                                        return <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4jzwox@${i}`} span = {3} style={{paddingTop: 7}}>
                                            <div>
                                                {item.weekday}
                                            </div>
                                            <br />
                                            <div>
                                                <strong>{item.date}</strong>
                                            </div>
                                        </Col>
                                    })
                                }
                            </Row>
                            <div className="body">
                                {
                                    hrmSystemInfo.bodyConf && !isEmpty(hrmSystemInfo.bodyConf) && hrmSystemInfo.bodyConf.map((conf, i) => {
                                    return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@cm4osn@${i}`} className={`bord-line ${conf.isRow? 'line': 'double'}`}>
                                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@5pg7kq@${i}`} span = {3} className="info-title">
                                                    <i className={conf.icon} />
                                                    {conf.title}
                                                </Col>
                                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@w7i0e1@${i}`} span = {3} className="picker-col">
                                                    <div>
                                                        <i className={conf.fieldsConf[0].icon} />
                                                        {conf.fieldsConf[0].title} :
                                                    </div>
                                                    {
                                                        conf.fieldsConf.length>1 && conf.fieldsConf[1] &&
                                                        <div>
                                                            <br />
                                                            {conf.fieldsConf[1].isIp ?
                                                                <span className={conf.fieldsConf[1].icon}>
                                                                    <span className="path1"></span>
                                                                    <span className="path2"></span>
                                                                    <span className="path3"></span>
                                                                </span>
                                                                :<i className={conf.fieldsConf[1].icon} />
                                                            }
                                                            {conf.fieldsConf[1].title} :
                                                        </div>
                                                    }
                                                </Col>
                                                {
                                                    weekInfo.weekInfo && !isEmpty(weekInfo.weekInfo) && weekInfo.weekInfo.map((item, i) => {
                                                        return <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ajwofd@${i}`} span = {3}>
                                                            <div className='text-overflow' title={item[conf.fields[0]]}>
                                                                {item[conf.fields[0]]}
                                                            </div>
                                                            {
                                                                conf.fields.length>1 && conf.fields[1] &&
                                                                <div className='text-overflow' title={item[conf.fields[1]]}>
                                                                    <br />
                                                                    {item[conf.fields[1]]}
                                                                </div>
                                                            }
                                                        </Col>
                                                    })
                                                }
                                            </Row>
                                    })
                                }
                            </div>
                        </WeaSearchGroup>
                    }
                    </div>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@irri0m`} 
                    title={i18n.confirm.defaultTitle()}
                    icon={"icon-coms02-Warning"}
                    iconBgcolor={"#ff9900"}
                    visible={modalVisible}
                    style={{width:380,height:100}}
                    buttons={(weakPasswordDisable === "0") ? weakPassBtns : weakPassBtns.slice(0,1) }
                >
                <p style={{lineHeight:"100px",textAlign:"center"}}>
                    {
                        (weakPasswordDisable === "0") ? getLabel('515419','该密码比较容易被猜到，确定保存吗？')  : getLabel('515420','该密码比较容易被猜到，为了您的系统安全，请重新修改密码。') 
                    }
                </p>

                </WeaDialog>
            </div>
            )
        }catch(e){
            return (
                <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@cjv00l`}>
                  <div style={{ color: '#000' }}>{i18n.message.authFailed()}</div>
              </WeaAlertPage>
              )
        }
    }

    getTopButtons = () => {
        const {hrmSystemInfo} = this.props;
        const {isEditor, buttons} = hrmSystemInfo;

        const save = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ny3cu6`} type="primary" onClick={this.doSave} >{i18n.button.save()}</Button>;
        const back = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xhll2y`} type="primary" onClick={this.backCard} >{i18n.button.back()}</Button>;
        const edit = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rj4oo3`} type="primary" onClick={this.edit} >{i18n.button.modify()}</Button>;
        const btns = [];
        try{
            if (isEditor) {
                if(buttons && buttons.hasEdit){
                btns.push(save);
                btns.push(back);
            }
            } else {
                if(buttons && buttons.hasEdit){
                    btns.push(edit);
                }
            }
        }catch(e){}
        return btns;
      }

    doSave = () => {
        const {hrmSystemInfo} = this.props;
        hrmSystemInfo.doSave();
    }
    
    edit = () => {
        const {hrmSystemInfo} = this.props;
        hrmSystemInfo.edit();
    }

    backCard = () => {
        const {hrmSystemInfo} = this.props;
        hrmSystemInfo.backCard();
    }
   
    updateKey = () => {
        const {hrmSystemInfo} = this.props;
        hrmSystemInfo.updateKey();
    }

    onPickerChange = (v) => {
        const {hrmSystemInfo} = this.props;
        hrmSystemInfo.onPickerChange(v);
    }

    onCheckChange = (v) => {
        const {hrmSystemInfo} = this.props;
        hrmSystemInfo.onCheckChange(v);
    }

    onSelectChange = (v) => {
        const {hrmSystemInfo} = this.props;
        hrmSystemInfo.onSelectChange(v);
    }

    getRightMenu = () => {
        const {hrmSystemInfo} = this.props;
        const {isEditor, buttons, hrmId} = hrmSystemInfo;

        let arr = [];
        try{
            if(buttons && buttons.hasEdit){
            if (isEditor){
                arr = [{
                    icon: <i className='icon-coms-common'/>,
                    content: i18n.button.save(),
                    key: 'save',
                    onClick: key =>{
                    this.doSave();
                    }
                }, {
                    icon: <i className='icon-coms-go-back'/>,
                    content: i18n.button.back(),
                    key: 'back',
                    onClick: key =>{
                    this.backCard();
                    }
                }]
            } else {
                arr = [{
                    icon: <i className='icon-coms-edit'/>,
                    content:i18n.button.modify(),
                    key: 'editCard',
                    onClick: key =>{
                        this.edit();
                    }
                    }]
                arr.push(
                    {
                        icon: <i className='icon-coms-Print-log'/>,
                        content:i18n.button.log(),
                        key: 'showLog',
                        onClick: key =>{
                            window.setLogViewProps({logSmallType:i18n.smallType.HRM_RSOURCE_CARD_SYSTEM,targetId:hrmId});
                        }
                    }
                )
            }
            }
        }catch(e){}
        return arr;
      }

      changeUsbstate = v =>{
        const {hrmSystemInfo:{form}} = this.props;
        form.updateFields({
            usbstate:{
                value : v
            }
        })
      }
}

export default HrmSystemInfo;